<?php

/**
 * @author gbfun <gbfun@163.com>  2018-05-28 16:35
 * http://www.wuweiyou.com
 */

class wwy_file_handler
{ 
    protected static $_instance = null;
    
    private function __clone()
    {
    }
    
    /**
     * @return wwy_file_handler
     */
    public static function get_instance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();    //by gbfun 又是静态变量
        }
    
        return self::$_instance;
    }
    
    protected function __construct()
    {
        
    }
    
    // 循环创建目录
	public function mk_dir($dir, $mode = 0777) 
	{
	    if (is_dir($dir) || @mkdir($dir, $mode)) {
	        return true;
	    }
	    if (!(self::mk_dir(dirname($dir), $mode))) {
	    	return false;
	    }
	        
	    return @mkdir($dir, $mode);
	}
	
	/** 
	 * Recursively delete a directory 
	 * 
	 * @param string $dir Directory name 
	 * @param boolean $delete_root_too Delete specified top-level directory as well 
	 */ 
	public function unlink_recursive($dir, $delete_root_too = false) 
	{ 
	    if (!$dh = @opendir($dir)) { 
	        return; 
	    } 
	    
	    while (false !== ($obj = readdir($dh))) { 
	        if ($obj == '.' || $obj == '..') { 
	            continue; 
	        } 
	
	        if (!@unlink($dir . '/' . $obj)) { 
	            self::unlinkRecursive($dir.'/'.$obj, true); 
	        } 
	    } 
	
	    closedir($dh); 
	    
	    if ($delete_root_too) { 
	        @rmdir($dir); 
	    } 
	}
	
	public function upload($tmp_name, $target)
	{
	    $result = $this->move_uploaded_file($tmp_name, $target);
	    
	    return $result;
	}
	
	public function move_uploaded_file($tmp_name, $target)
	{
	    $result = array('status' => 0, 'message' => '', 'data' => array());
	    
	    if (!$this->mk_dir(dirname($target))) {
	        $result['status']  = -400;
	        $result['message'] = "无权限创建目录-' . $target .'";
	
	        return $result;
	    }
	     
	    if (!move_uploaded_file($tmp_name, $target)) {
	        $result['status']  = -400;
	        $result['message'] = '上传失败';
	
	        return $result;
	    }
	     
	    $result['status']  = 1;
	    $result['message'] = '上传成功';
	
	    return $result;
	}
}
